﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using IronOne.SalesOne.BusinessObjects;


namespace IronOne.SalesOne.SalesOneWeb.UserManagement
{
    public partial class SearchMessages :SOSecurityPage, IDataPage
    {
        Facade.StructureFacade structureFacade = new Facade.StructureFacade();
        Facade.MessageFacade messageFacade = new Facade.MessageFacade();
        static List<Branch> lstBranches = new List<Branch>();
        static List<SalesOneUnit> lstUnits = new List<SalesOneUnit>();
        static List<string> lstSocodes = new List<string>();

        static string userName ;

        protected void Page_Load(object sender, EventArgs e)
        {
            UCGridButtons1.SetCredentials(ValidateUserCredentials(Request.Url.LocalPath));
            if (!IsPostBack)
            {
                                /*Get The current User*/
                MembershipUser user = Membership.GetUser(HttpContext.Current.User.Identity.Name);
                userName = user.UserName;
                //SetDataSourceToFrom(structureFacade.GetUserTypesForUser("UserTypeName ASC",user.UserName)); 
                SetDataSourceToFrom(structureFacade.GetUserTypesForUser("UserTypeId ASC", userName));
            }
            lblError.ForeColor = Color.Black;
            lblError.Text = "";
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Create();
        }

        public void SetDataSourceToBranches(List<Branch> branches)
        {
            ddlBranch.DataSource = branches;
            ddlBranch.DataTextField = "BranchName";
            ddlBranch.DataValueField = "BranchID";
            ddlBranch.DataBind();

            InsertDDLItems(ddlBranch, "Select...", 0);
            InsertDDLItems(ddlBranch, "Select All", 1);
        }

        public void SetDataSourceToUnits(List<SalesOneUnit> units)
        {
            ddlUnit.DataSource = units;
            ddlUnit.DataTextField = "Name";
            ddlUnit.DataValueField = "UnitId";
            ddlUnit.DataBind();

            InsertDDLItems(ddlUnit, "Select...", 0);
            InsertDDLItems(ddlUnit, "Select All", 1);
        }

        public void SetDataSourceToSoCode(List<string> users)
        {
            ddlSOCode.DataSource = users;
            ddlSOCode.DataBind();

            InsertDDLItems(ddlSOCode, "Select...", 0);
            InsertDDLItems(ddlSOCode, "Select All", 1);
        }

        public void SetDataSourceToSoCode(List<User> users)
        {
            ddlSOCode.DataSource = users;
            ddlSOCode.DataTextField = "Name";
            ddlSOCode.DataValueField = "UserId";
            ddlSOCode.DataBind();

            InsertDDLItems(ddlSOCode, "Select...", 0);
            InsertDDLItems(ddlSOCode, "Select All", 1);
        }

        public void SetDataSourceToFrom(List<UserType> userTypes)
        {
            ddlFrom.DataSource = userTypes;
            ddlFrom.DataTextField = "UserTypeName";
            ddlFrom.DataValueField = "UserTypeId";
            ddlFrom.DataBind();

            InsertDDLItems(ddlFrom, "Select...", 0);
            //InsertDDLItems(ddlFrom, "Select All", 1);
        }

        public void InsertDDLItems(DropDownList ddl, string Text, int Position)
        {
            ListItem item = new ListItem(Text,Text);
            ddl.Items.Insert(Position, Text);
            //ddl.Items.Add( item);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (ddlFrom.SelectedIndex > 0)
            {
                SearchMessage searchMessage = new SearchMessage();
                searchMessage.UserType = Convert.ToInt32(ddlFrom.SelectedValue);
                searchMessage.Broadcasted = chkBroadcast.Checked;

                if (ddlBranch.SelectedIndex > 0)
                {
                    if (ddlBranch.SelectedIndex == 1)
                        searchMessage.Branches=lstBranches;
                    else
                    {
                        List<Branch> lst=new List<Branch>();
                        lst.Add(lstBranches.Find(GetBranch));
                        searchMessage.Branches =lst;
                    }
                        
                }
                if (ddlUnit.SelectedIndex > 0)
                {
                    if (ddlUnit.SelectedIndex == 1)
                        searchMessage.Units = lstUnits;
                    else
                    {
                        List<SalesOneUnit> lst = new List<SalesOneUnit>();
                        lst.Add(lstUnits.Find(GetUnit));
                        searchMessage.Units = lst;
                    }

                }
                if (ddlSOCode.SelectedIndex > 0)
                {
                    if (ddlSOCode.SelectedIndex == 1)
                        searchMessage.SOCodes = lstSocodes;
                    else
                    {
                        List<string> lst = new List<string>();
                        lst.Add(lstSocodes.Find(GetSOCode));
                        searchMessage.SOCodes = lst;
                    }
                }
                //int[] numbers = {};
                int[] numbers = {7,8,9,10,11,12,13,14,15,16};
                List<Message> messages=messageFacade.SearchMessages(searchMessage);
                if (messages.Count > 0)
                {
                    UCGrid1.SetDataSource(messages, numbers);
                    UCGridButtons1.Visible = true;
                    UCGrid1.Visible = true;
                }
                else
                {
                    UCGridButtons1.Visible = false;
                    UCGrid1.Visible =false;
                }

            }
            else
            {
                lblError.ForeColor = Color.Red;
                lblError.Text = "Please select a user type.";
            }
        }

        protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            EnableControls(true);
            if (ddlBranch.SelectedIndex > 1)
            {
                lstUnits=structureFacade.GetUnitsInBranch(int.Parse(ddlBranch.SelectedValue));
                SetDataSourceToUnits(lstUnits);
            }
            else if (ddlBranch.SelectedIndex == 1)
            {
                ddlUnit.Enabled = false;
                ddlUnit.Items.Clear();
                ddlSOCode.Enabled = false;
                ddlSOCode.Items.Clear();
            }
        }

        protected void chkBroadcast_CheckedChanged(object sender, EventArgs e)
        {
            DisableControlsForBroadcasting();
        }

        public void DisableControlsForBroadcasting()
        {
            if (chkBroadcast.Checked)
            {
                EnableControls(false);
            }
            else
            {
                EnableControls(true);
            }
        }

        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            EnableControls(true);
            if (ddlUnit.SelectedIndex > 1)
            {
                lstSocodes = structureFacade.GetSOsInUnit(int.Parse(ddlUnit.SelectedValue));
                SetDataSourceToSoCode(lstSocodes);
            }
            else if (ddlUnit.SelectedIndex == 1)
            {
                ddlSOCode.Enabled = false;
                ddlSOCode.Items.Clear();
            }
        }

        protected void ddlFrom_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlFrom.SelectedIndex > 0)
            {
                if (ddlFrom.SelectedItem.Text.Equals("HQ", StringComparison.InvariantCultureIgnoreCase))
                {
                    chkBroadcast.Enabled = true;
                    lstBranches = structureFacade.GetBranches("BranchName ASC");
                    SetDataSourceToBranches(lstBranches);
                }
                /*If Group selected populate the branches according to the group*/
                else if (ddlFrom.SelectedItem.Text.Equals("Group", StringComparison.InvariantCultureIgnoreCase))
                {
                    DisableControlsForHQ();
                    lstBranches = structureFacade.GetBranchesForGroup("BranchName ASC", userName);
                    SetDataSourceToBranches(lstBranches);
                    //populate branches
                }
                /*If brnch - populate the branches according to the selected branch */
                else if (ddlFrom.SelectedItem.Text.Equals("Branch", StringComparison.InvariantCultureIgnoreCase))
                {
                    DisableControlsForHQ();
                    //populate units
                    lstUnits = structureFacade.GetUnitsInBranch("UnitName", userName);
                    SetDataSourceToUnits(lstUnits);
                }
                /*If units then -units acoording to the .....*/
                else if (ddlFrom.SelectedItem.Text.Equals("Unit", StringComparison.InvariantCultureIgnoreCase))
                {
                    lstSocodes = structureFacade.GetSOsForUser("", userName);
                    SetDataSourceToSoCode(lstSocodes);
                    DisableControlsForHQ();
                    //populate socodes
                }
            }
        }

        public void DisableControlsForHQ()
        {
            chkBroadcast.Enabled = false;
            chkBroadcast.Checked = false;
            DisableControlsForBroadcasting();
        }

        public void EnableControls(bool enabled)
        {
            ddlBranch.Enabled = enabled;
            ddlUnit.Enabled = enabled;
            ddlSOCode.Enabled = enabled;
        }
        
        private bool GetBranch(Branch branch)
        {
            if (branch.BranchId == Convert.ToInt32(ddlBranch.SelectedValue))
                return true;
            else
                return false;

        }

        private bool GetUnit(SalesOneUnit unit)
        {
            if (unit.UnitId == Convert.ToInt32(ddlUnit.SelectedValue))
                return true;
            else
                return false;
        }

        private bool GetSOCode(string soCode)
        {
            if (soCode.Equals(ddlSOCode.SelectedItem.Text))
                return true;
            else
                return false;

        }

        #region IDataPage Members

        public void Create()
        {
            Response.Redirect("~/Messaging/CreateMessage.aspx");
        }

        public void View()
        {
            Response.Redirect("~/Messaging/ViewMessage.aspx?MessageId=" + Session["messgeId"].ToString());
        }

        public void Update()
        {
            Response.Redirect("~/Messaging/UpdateMessage.aspx?MessageId=" + Session["messgeId"].ToString());
        }

        public void Delete()
        {
            try
            {
                string msgId = Session["messgeId"].ToString();
                Message message = messageFacade.GetMessage(Convert.ToInt32(msgId));
                messageFacade.DeleteMessage(message);
            }catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        public void Cancel()
        {

        }

        #endregion



        #region IDataPage Members


        public void GetId(GridViewRow row)
        {
            Session["messgeId"] = row.Cells[7].Text;
        }

        #endregion

        /*Appendix*/
        //searchMessage.Units=
        //searchMessage.SOCodes=

        //if (ddlFrom.SelectedIndex == 1)
        //    //UCGrid1.SetDataSource(messageFacade.GetMessages("MessageId ASC"));
        //    UCGrid1.SetDataSource(messageFacade.SearchMessages(5,true,1,1,"1212"));
        //else
        //    UCGrid1.SetDataSource(messageFacade.GetMessagesSentBy(Convert.ToInt32(ddlFrom.SelectedValue)));

        /*
        if (ddlSOCode.SelectedIndex > 0)
        {
            if(ddlSOCode.SelectedIndex==1)
                messageFacade.SearchMessages(Convert.ToInt32(ddlFrom.SelectedValue), false, -1, -1, "*");
            else
                messageFacade.SearchMessages(Convert.ToInt32(ddlFrom.SelectedValue), false, -1, -1, ddlSOCode.SelectedItem.Text);
        }
        else if (ddlUnit.SelectedIndex > 0)
        {
            if (ddlUnit.SelectedIndex == 1)
                messageFacade.SearchMessages(Convert.ToInt32(ddlFrom.SelectedValue), false, -1, 0, "");
            else
                messageFacade.SearchMessages(Convert.ToInt32(ddlFrom.SelectedValue), false, -1, Convert.ToInt32(ddlUnit.SelectedValue), "");
        }
        else if (ddlBranch.SelectedIndex > 0)
        {
            if (ddlBranch.SelectedIndex == 1)
                messageFacade.SearchMessages(Convert.ToInt32(ddlFrom.SelectedValue), false, 0, -1, "");
            else
                messageFacade.SearchMessages(Convert.ToInt32(ddlFrom.SelectedValue), false, Convert.ToInt32(ddlBranch.SelectedValue), -1, "");
        }
        else if (chkBroadcast.Checked)
        {
            messageFacade.SearchMessages(Convert.ToInt32(ddlFrom.SelectedValue), true, -1, -1, "");
        }
        else
            messageFacade.SearchMessages(Convert.ToInt32(ddlFrom.SelectedValue), false, -1, -1, "");

        //int userTypeID;
        //if(ddlFrom.SelectedValue)
        //{
        //    userTypeID= Convert.ToInt32(ddlFrom.SelectedValue));
         * */

    }
}
